package com.guota.controller;

import com.guota.pojo.Student;
import com.guota.pojo.Teacher;
import com.guota.service.StudentFeign;
import com.guota.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

@RestController
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private StudentFeign sf;


    /*@Autowired
    private RestTemplate restTemplate;  // 请求

    @Autowired
    private LoadBalancerClient loadBalancerClient;  // 自动获取地址*/

    @Autowired
    private TeacherService teacherService;

    @GetMapping("/findOne/{id}")
    public Teacher findOne(@PathVariable Integer id){
        return teacherService.findOneTea(id);
    }
    @PostMapping("/edit")
    public String editTea(@RequestBody Teacher teacher){
        teacherService.editTea(teacher);
        return "成功";
    }
    @PostMapping("/insert")
    public String insert(@RequestBody Teacher teacher){
        teacherService.insertTea(teacher);
        return "成功";
    }
    @DeleteMapping("/del/{id}")
    public String del(@PathVariable Integer id){
        //ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-student");
        Teacher teacher = teacherService.findById(id);
        teacherService.del(id);
        String sid = teacher.getSid();
        if (sid==null && sid==""){
            return "成功";
        }
        String[] split = sid.split(",");
        for (String s : split) {
            Integer of = Integer.valueOf(s);
            sf.edit(of);
        }
        return "成功";
    }
    @GetMapping("/findAll/{id}")
    public Teacher findAll(@PathVariable Integer id){
        Teacher teacher=teacherService.findById(id);
        String sid = teacher.getSid();
        String[] split = sid.split(",");
        ArrayList<Student> students = new ArrayList<>();
        for (String s : split) {
            Integer of = Integer.valueOf(s);
            Student all = sf.findAll(of);
            students.add(all);
        }
        teacher.setStudents(students);
        return teacher;
    }

}
